﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

/// <summary>
/// Summary description for ManageXMLController
/// </summary>
public class ManageXMLController
{
	public ManageXMLController()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /// <summary>
    /// Method that uses recursion to drill down and return a set of active (those are having urls) site map nodes
    /// </summary>
    /// <param name="dataList"></param>
    /// <param name="rootNode"></param>
    /// <returns></returns>
    private static List<XMLSiteMapParserObject> GetXMLSiteMapNodeList(List<XMLSiteMapParserObject> dataList, XmlNode rootNode)
    {
        if (rootNode != null)
        {
            XmlNodeList nodeList = rootNode.ChildNodes;

            foreach (XmlNode node in nodeList)
            {
                if (node.Name.ToLower().Equals("sitemapnode") && node.Attributes["url"] != null && !string.IsNullOrEmpty(node.Attributes["url"].Value))
                {
                    XMLSiteMapParserObject parserObject = new XMLSiteMapParserObject();

                    parserObject.Title = node.Attributes["title"].Value;
                    parserObject.URL = node.Attributes["url"].Value;
                    parserObject.Description = node.Attributes["description"].Value;

                    dataList.Add(parserObject);
                }
                if (node.ChildNodes.Count > 0)
                {
                    dataList = GetXMLSiteMapNodeList(dataList, node);
                }
            }
        }

        return dataList;
    }

    /// <summary>
    /// Utility method to read sitemap nodes.
    /// This method will only return a list of site map nodes that are having urls.
    /// </summary>
    /// <returns></returns>
    public static List<XMLSiteMapParserObject> ReadSiteMapNodes()
    {
        XmlDocument xmlDoc = new XmlDocument();

        try
        {
            xmlDoc.Load( HttpContext.Current.Server.MapPath("~/Web.sitemap"));
        }
        catch (Exception ex)
        {
            return null;
        }

        if (xmlDoc != null)
        {
            XmlNode rootNode = xmlDoc.DocumentElement;
            List<XMLSiteMapParserObject> dataList = new List<XMLSiteMapParserObject>();

            return GetXMLSiteMapNodeList(dataList, rootNode);
        }

        return null;
    }
}
